package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
	"vrcm/src/vrcm/app/admin/models/live_schedule"
	baiduService "vrcm/src/vrcm/app/admin/service/baidu"
	baiduDto "vrcm/src/vrcm/app/admin/service/dto/baidu"
	liveDto "vrcm/src/vrcm/app/admin/service/dto/live"
	"vrcm/src/vrcm/app/admin/service/dto/live_schedule"
	StreamHubDto "vrcm/src/vrcm/app/admin/service/dto/stream_hub"
	liveService "vrcm/src/vrcm/app/admin/service/live"
	streamHubService "vrcm/src/vrcm/app/admin/service/stream_hub"
	"vrcm/src/vrcm/common/apis"
	commonDto "vrcm/src/vrcm/common/dto"
	"vrcm/src/vrcm/common/service"

	"gorm.io/gorm"

	cDto "vrcm/src/vrcm/common/dto"
)

type ChannelBasicService struct {
	service.Service
}

// GetPage 获取ChannelBasic列表
func (e *ChannelBasicService) GetPage(c *dto.ChannelBasicGetPageReq, list *[]live_schedule.ChannelBasic, count *int64) error {
	var err error
	var data live_schedule.ChannelBasic
	basicService := &SourceBasicService{}
	basicService.Orm = e.Orm
	basicService.Log = e.Log

	db := e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		)
	if len(c.TenantId) > 0 {
		db.Where("tenant_id = ?", c.TenantId)
	}

	if c.ChannelId > 0 {
		db.Where("id = ?", c.ChannelId)
	}

	if c.IsDelete == 2 {
		db.Where("is_delete = ?", c.IsDelete)
	} else {
		db.Order("is_delete desc")
	}

	err = db.Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("ChannelBasicService GetPage error:%s \r\n", err)
		return err
	}

	ids := make([]int, 0, 5)
	for _, v := range *list {
		ids = append(ids, v.Id)
	}

	//获取上车点和媒体处理的关系
	upMedias := make([]live_schedule.UpMedia, 0, 5)
	err = e.Orm.Model(&live_schedule.UpMedia{}).Where("channel_id in ?", ids).Find(&upMedias).Error
	if err != nil {
		e.Log.Errorf("get upMedias error:%s \r\n", err)
		return err
	}
	//获取媒体处理
	medias := make([]live_schedule.MediaProcess, 0, 5)
	err = e.Orm.Model(&live_schedule.MediaProcess{}).Where("channel_id in ? and media_type!=3", ids).Find(&medias).Error
	if err != nil {
		e.Log.Errorf("get MediaProcess error:%s \r\n", err)
		return err
	}
	mediaChannelMap := make(map[int]live_schedule.MediaProcess)
	for _, v := range medias {
		v := v
		mediaChannelMap[v.ChannelId] = v
	}
	upIds := make([]int, 0, 5)
	for _, v := range upMedias {
		upIds = append(upIds, v.UpId)
	}

	//获取上车点
	trafficOns := make([]live_schedule.TrafficOn, 0, 5)
	err = e.Orm.Model(&live_schedule.TrafficOn{}).Where("id in ?", upIds).Find(&trafficOns).Error
	if err != nil {
		e.Log.Errorf("get TrafficOn error:%s \r\n", err)
		return err
	}
	//存储信源和调度任务关系
	sourceIds := make([]int, 0, 5)
	taskSourceMap := make(map[int][]int)
	tagMap := make(map[int]struct{})
	for _, v := range trafficOns {
		v := v
		sources, ok1 := taskSourceMap[v.ChannelId]
		if !ok1 {
			sources = make([]int, 0, 5)
		}
		_, ok2 := tagMap[v.SourceId]
		if !ok2 {
			sources = append(sources, v.SourceId)
			tagMap[v.SourceId] = struct{}{}
			sourceIds = append(sourceIds, v.SourceId)
		}
		taskSourceMap[v.ChannelId] = sources
	}

	//获取信源详情
	sourceMap := make(map[int]live_schedule.SourceBasic)
	//信源状态映射
	sourceStateMap := make(map[int]int)
	var count1 int64
	pagination := commonDto.Pagination{PageIndex: 1, PageSize: 1000}
	if len(sourceIds) > 0 {
		basics, err := basicService.GetPage(&dto.SourceBasicGetPageReq{Pagination: pagination, SourceIds: sourceIds, IsDelete: 2}, &count1)
		if err != nil {
			e.Log.Errorf("GetSourceBasic error:%s \r\n", err)
			return err
		}
		for _, v := range *basics {
			v := v
			sourceMap[v.Basic.Id] = *v.Basic
			sourceStateMap[v.Basic.Id] = v.Basic.SourceState
		}
	}

	now := time.Now().Unix()
	//如果上线的通道任务里有异常 则通道为异常
	for k, v := range *list {
		if v.IsTime == 1 {
			cycleTimes := make([]live_schedule.CycleTime, 3)
			err = e.Orm.Model(&live_schedule.CycleTime{}).Where("channel_id = ? and time_type=? and start_time>? and is_cancel = 2", v.Id, v.TimeType, now).Find(&cycleTimes).Error
			if err != nil {
				e.Log.Errorf("get CycleTime error:%s \r\n", err)
				return err
			}
			if len(cycleTimes) > 0 {
				(*list)[k].NextStartTime = cycleTimes[0].StartTime
			}
			if v.TimeType == 1 && v.StartTime > now {
				(*list)[k].NextStartTime = v.StartTime
			}
		}
		if v.ChannelState == 2 {
			continue
		}
		//获取信源
		sources, ok := taskSourceMap[v.Id]
		if !ok {
			continue
		}
		isException := false
		//信源如果异常或者离线通道状态均为异常
		for _, s := range sources {
			state := sourceStateMap[s]
			if state == 3 {
				isException = true
				break
			}
		}
		//如果有异常
		if isException {
			(*list)[k].ChannelState = 3
		}

	}
	return nil
}

// Get 获取ChannelBasic对象
func (e *ChannelBasicService) Get(d *dto.ChannelBasicGetReq, model *live_schedule.ChannelBasic) error {
	var data live_schedule.ChannelBasic
	basicService := &SourceBasicService{}
	basicService.Orm = e.Orm
	basicService.Log = e.Log

	err := e.Orm.Model(&data).
		First(model, d.GetId()).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		e.Log.Errorf("Service GetChannelBasic error:%s \r\n", err)
		return err
	}
	var media live_schedule.MediaProcess
	err = e.Orm.Model(&live_schedule.MediaProcess{}).Where("channel_id=? and media_type!=3", d.Id).Find(&media).Error
	if err != nil {
		e.Log.Errorf("get MediaProcess error:%s \r\n", err)
		return err
	}
	//存储信源
	sourceIds := make([]int, 0, 5)
	if media.MediaType == 1 {
		//获取调度任务
		tasks := make([]live_schedule.ChannelTask, 0, 5)
		err = e.Orm.Model(live_schedule.ChannelTask{}).Where("channel_id = ?", d.GetId()).Find(&tasks).Error
		if err != nil {
			e.Log.Errorf("get ChannelTask error:%s \r\n", err)
			return err
		}
		for _, v := range tasks {
			v := v
			sourceIds = append(sourceIds, v.SourceId)
		}
	} else {
		//获取调度任务
		tasks := make([]live_schedule.CortexTask, 0, 5)
		err = e.Orm.Model(live_schedule.CortexTask{}).Where("channel_id = ?", d.GetId()).Find(&tasks).Error
		if err != nil {
			e.Log.Errorf("get CortexTask error:%s \r\n", err)
			return err
		}
		for _, v := range tasks {
			v := v
			sourceIds = append(sourceIds, v.SourceId)
		}
	}
	//获取信源详情
	var count1 int64
	isException := false
	pagination := commonDto.Pagination{PageIndex: 1, PageSize: 1000}
	if len(sourceIds) > 0 {
		basics, err := basicService.GetPage(&dto.SourceBasicGetPageReq{Pagination: pagination, SourceIds: sourceIds, IsDelete: 2}, &count1)
		if err != nil {
			e.Log.Errorf("GetSourceBasic error:%s \r\n", err)
			return err
		}
		for _, v := range *basics {
			v := v
			if v.Basic.SourceState == 3 {
				isException = true
				break
			}
		}
	}
	//如果上线的通道任务里有异常 则通道为异常
	if model.ChannelState == 1 && isException {
		model.ChannelState = 3
	}
	return nil
}

func (e *ChannelBasicService) Get1(d *dto.ChannelBasicGetReq, model *live_schedule.ChannelBasic) error {
	var data live_schedule.ChannelBasic
	basicService := &SourceBasicService{}
	basicService.Orm = e.Orm
	basicService.Log = e.Log

	err := e.Orm.Model(&data).
		First(model, d.GetId()).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		e.Log.Errorf("Service GetChannelBasic error:%s \r\n", err)
		return err
	}

	chartData := live_schedule.ChartData{}
	if len(model.ChartData) > 0 {

		err = json.Unmarshal([]byte(model.ChartData), &chartData)
		if err != nil {
			e.Log.Errorf("Unmarshal ChartData error:%s \r\n", err)
			return err
		}
	}

	//获取信源详情
	var count1 int64
	isException := false
	pagination := commonDto.Pagination{PageIndex: 1, PageSize: 1000}
	sourceMap := make(map[int]live_schedule.SourceBasic)
	sourceDetailMap := make(map[int][]live_schedule.SourceDetailModel)
	basics, err := basicService.GetPage(&dto.SourceBasicGetPageReq{Pagination: pagination, IsDelete: 2, TenantId: model.TenantId, Kind: 3}, &count1)
	if err != nil {
		e.Log.Errorf("GetSourceBasic error:%s \r\n", err)
		return err
	}
	for _, v := range *basics {
		v := v
		sourceMap[v.Basic.Id] = *v.Basic
		sourceDetailMap[v.Basic.Id] = v.Details
		//if v.Basic.SourceState == 3 {
		//	isException = true
		//	break
		//}

	}
	for k, nodeData := range chartData.NodeData {
		nodeData := nodeData
		switch nodeData.Node.Data.Type {
		case "input":

			sourceState := sourceMap[nodeData.Node.Data.FormData.SourceId].SourceState
			*(&chartData.NodeData[k].Node.Data.NodeState) = sourceState
			*(&chartData.NodeData[k].Node.Data.TaskId) = sourceMap[nodeData.Node.Data.FormData.SourceId].TaskId
			*(&chartData.NodeData[k].Node.Data.Area) = sourceMap[nodeData.Node.Data.FormData.SourceId].Area
			details := sourceDetailMap[nodeData.Node.Data.FormData.SourceId]
			if len(details) > 0 {
				*(&chartData.NodeData[k].Node.Data.SourceUrl) = details[0].SourceDetail.SourceUrl
				*(&chartData.NodeData[k].Node.Data.OutUrls[0].OutputUrl) = sourceMap[nodeData.Node.Data.FormData.SourceId].OutUdpUrl
				*(&chartData.NodeData[k].Node.Data.OutUrls[0].NodeId) = details[0].SourceDetail.NodeId
			}

		case "media_switch":
			//switchTask := live_schedule.SwitchTask{}
			//err = e.Orm.Model(&live_schedule.SwitchTask{}).Where("channel_id=? and media_id=?", d.Id, nodeData.Node.Id).Find(&switchTask).Error
			//if err != nil {
			//	e.Log.Errorf("SwitchTask error:%s \r\n", err)
			//	return err
			//}
			//if switchTask.TaskState == 2 {
			//	switchTask.TaskState = 3
			//}
			//if switchTask.TaskState == 3 {
			//	switchTask.TaskState = 2
			//}
			//*(&chartData.NodeData[k].Node.Data.NodeState) = switchTask.TaskState
		case "media_trans":
			//channelTransTask := live_schedule.ChannelTransTask{}
			//err = e.Orm.Model(&live_schedule.ChannelTransTask{}).Where("channel_id=? and media_id=?", d.Id, nodeData.Node.Id).Find(&channelTransTask).Error
			//if err != nil {
			//	e.Log.Errorf("get ChannelTransTask error:%s \r\n", err)
			//	return err
			//}
			//if channelTransTask.TaskState == 2 {
			//	channelTransTask.TaskState = 3
			//}
			//if channelTransTask.TaskState == 3 {
			//	channelTransTask.TaskState = 2
			//}
			//*(&chartData.NodeData[k].Node.Data.NodeState) = channelTransTask.TaskState
		case "output":
			covertTask := live_schedule.CovertTask{}
			err = e.Orm.Model(&live_schedule.CovertTask{}).Where("channel_id=? and media_id=?", d.Id, nodeData.Node.Id).Find(&covertTask).Error
			if err != nil {
				e.Log.Errorf("get CovertTask error:%s \r\n", err)
				return err
			}
			if covertTask.TaskState == 2 {
				covertTask.TaskState = 3
			}
			if covertTask.TaskState == 3 {
				covertTask.TaskState = 2
			}
			*(&chartData.NodeData[k].Node.Data.NodeState) = covertTask.TaskState
			*(&chartData.NodeData[k].Node.Data.SourceUrl) = covertTask.OutUrl
		}
	}
	if len(chartData.NodeData) > 0 {
		chartDataByte, err := json.Marshal(&chartData)
		if err != nil {
			e.Log.Errorf("Marshal chartData error:%s \r\n", err)
			return err
		}
		err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("id=?", d.Id).Update("chart_data", string(chartDataByte)).Error
		if err != nil {
			e.Log.Errorf("update ChannelBasic error:%s \r\n", err)
			return err
		}
	}

	err = e.Orm.Model(&model).
		First(model, d.GetId()).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		e.Log.Errorf("Service GetChannelBasic error:%s \r\n", err)
		return err
	}

	//如果上线的通道任务里有异常 则通道为异常
	if model.ChannelState == 1 && isException {
		model.ChannelState = 3
	}
	return nil
}

// Insert 创建ChannelBasic对象
func (e *ChannelBasicService) Insert(c *dto.ChannelBasicInsertReq) error {
	var err error
	var data live_schedule.ChannelBasic

	//err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("channel_name=? and is_delete=2", c.ChannelName).Find(&data).Error
	//if err != nil {
	//	e.Log.Errorf("get ChannelBasic error:%s \r\n", err)
	//	return err
	//}
	//if data.Id > 0 {
	//	return errors.New("Duplicate entry")
	//}
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("ChannelBasicService Insert error:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

// Update 修改ChannelBasic对象
func (e *ChannelBasicService) Update(c *dto.ChannelBasicUpdateReq) error {
	var err error
	var data = live_schedule.ChannelBasic{}
	//err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("channel_name=? and id !=? and is_delete=2", c.ChannelName, c.Id).Find(&data).Error
	//if err != nil {
	//	e.Log.Errorf("get ChannelBasic error:%s \r\n", err)
	//	return err
	//}
	//if data.Id > 0 {
	//	return errors.New("Duplicate entry")
	//}
	e.Orm.First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("ChannelBasicService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除ChannelBasic
func (e *ChannelBasicService) Remove(d *dto.ChannelBasicDeleteReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			e.Log.Errorf("Service RemoveChannelBasic error:%s \r\n", r)
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		e.Log.Errorf("Service RemoveChannelBasic error:%s \r\n", err)
		return err
	}
	streamHubService := &streamHubService.StreamHubService{}
	liveService := &liveService.LiveBasic{}
	baiduService := &baiduService.BaiduService{}
	streamHubService.Log = e.Log
	liveService.Log = e.Log
	baiduService.Log = e.Log
	sourceBasicService := SourceBasicService{}
	sourceBasicService.Log = e.Log
	sourceBasicService.Orm = e.Orm
	//var data live_schedule.ChannelBasic

	basics := make([]live_schedule.ChannelBasic, 0, 5)
	err := tx.Model(live_schedule.ChannelBasic{}).Where("id in ?", d.Ids).Find(&basics).Error
	if err != nil {
		e.Log.Errorf("get ChannelBasic error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	for _, v := range basics {
		if v.ChannelState != 2 {
			e.Log.Errorf("get ChannelBasic error:%s \r\n", err)
			tx.Rollback()
			return errors.New("该任务已启用")
		}
	}

	//获取媒体处理
	upMedias := make([]live_schedule.UpMedia, 0, 5)
	err = tx.Model(live_schedule.UpMedia{}).Where("channel_id in ?", d.Ids).Find(&upMedias).Error
	if err != nil {
		e.Log.Errorf("get upMedia error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	upIds := make([]int, 0, 5)
	for _, v := range upMedias {
		upIds = append(upIds, v.UpId)
	}

	//获取上车点的信源
	sourceIds := make([]int, 0, 5)
	err = tx.Model(live_schedule.TrafficOn{}).Distinct("source_id").Select("source_id").Where("channel_id in ?", d.Ids).Find(&sourceIds).Error
	if err != nil {
		e.Log.Errorf("get TrafficOn error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//获取信源
	sources := make([]live_schedule.SourceBasic, 0, 5)
	err = tx.Model(live_schedule.SourceBasic{}).Where("id in ?", sourceIds).Find(&sources).Error
	if err != nil {
		e.Log.Errorf("get SourceBasic error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	sourceMap := make(map[int]live_schedule.SourceBasic)
	for _, v := range sources {
		v := v
		sourceMap[v.Id] = v
	}

	err = tx.Model(&live_schedule.ChannelBasic{}).Where("id in ?", d.Ids).Update("is_delete", 1).Error
	if err != nil {
		e.Log.Errorf("update ChannelBasic error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	//db := tx.Model(&data).Delete(&data, d.GetId())
	//if err = db.Error; err != nil {
	//	e.Log.Errorf("Service RemoveChannelBasic error:%s \r\n", err)
	//	tx.Rollback()
	//	return err
	//}
	tasks := make([]live_schedule.ChannelTask, 0, 5)
	err = tx.Model(live_schedule.ChannelTask{}).Where("channel_id in ?", d.Ids).Find(&tasks).Error
	if err != nil {
		e.Log.Errorf("Service getChannelTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	for _, v := range tasks {
		v := v
		if len(v.TaskId) > 0 {
			streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
			if err != nil {
				e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service RemoveLive error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

	}

	switchTasks := make([]live_schedule.SwitchTask, 0, 5)
	err = tx.Model(live_schedule.SwitchTask{}).Where("channel_id in ?", d.Ids).Find(&switchTasks).Error
	if err != nil {
		e.Log.Errorf("get SwitchTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	for _, switchTask := range switchTasks {
		if len(switchTask.TaskId) > 0 {
			err = streamHubService.StopSwitchSource(&StreamHubDto.StartOrStopSwitchSourceReq{TenantId: switchTask.TenantId, Id: switchTask.TaskId})
			if err != nil {
				e.Log.Errorf("Service StopSwitchSource error:%s \r\n", err)
				tx.Rollback()
				return err
			}
			err = streamHubService.DeleteSwitchSourceTask(&StreamHubDto.SwitchSourceReq{TenantId: switchTask.TenantId, Id: switchTask.TaskId})
			if err != nil {
				e.Log.Errorf("Service DeleteSwitchSourceTask error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	err = tx.Model(live_schedule.SwitchTask{}).Where("channel_id in ?", d.Ids).Delete(&switchTasks).Error
	if err != nil {
		e.Log.Errorf("delete SwitchTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	channelTransTasks := make([]live_schedule.ChannelTransTask, 0, 5)
	err = e.Orm.Model(&live_schedule.ChannelTransTask{}).Where("channel_id in ?", d.Ids).Find(&channelTransTasks).Error
	if err != nil {
		e.Log.Errorf("delete ChannelTransTask error:%s \r\n", err)
		return err
	}

	for _, channelTransTask := range channelTransTasks {
		err = streamHubService.StopTransCode(&StreamHubDto.TransCodeReq{TenantId: channelTransTask.TenantId, Id: channelTransTask.TaskId})
		if err != nil {
			e.Log.Errorf("StopTransCode error:%s \r\n", err)
			//tx.Rollback()
			//return err
		}
		err = streamHubService.DeleteTransCode(&StreamHubDto.TransCodeReq{TenantId: channelTransTask.TenantId, Id: channelTransTask.TaskId})
		if err != nil {
			e.Log.Errorf("DeleteTransCode error:%s \r\n", err)
			//tx.Rollback()
			//return err
		}
	}

	err = tx.Model(live_schedule.ChannelTransTask{}).Where("channel_id in ?", d.Ids).Delete(&channelTransTasks).Error
	if err != nil {
		e.Log.Errorf("delete channelTransTasks error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	covertTasks := make([]live_schedule.CovertTask, 0, 5)
	err = tx.Model(live_schedule.CovertTask{}).Where("channel_id in ?", d.Ids).Find(&covertTasks).Error
	if err != nil {
		e.Log.Errorf("get CovertTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	for _, covertTask := range covertTasks {
		err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: covertTask.TenantId, Id: covertTask.TaskId})
		if err != nil {
			e.Log.Errorf("RemoveStreamHub error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if len(covertTask.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: covertTask.TenantId, LiveId: covertTask.LiveId})
			if err != nil {
				e.Log.Errorf("RemoveLive error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	err = tx.Model(live_schedule.CovertTask{}).Where("channel_id in ?", d.Ids).Delete(&covertTasks).Error
	if err != nil {
		e.Log.Errorf("delete CovertTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//获取软矩阵任务
	cortexTasks := make([]live_schedule.CortexTask, 0, 5)
	err = tx.Model(live_schedule.CortexTask{}).Where("channel_id in ?", d.Ids).Find(&cortexTasks).Error
	if err != nil {
		e.Log.Errorf("get CortexTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	//删除软矩阵任务
	for _, v := range cortexTasks {
		v := v
		if len(v.TaskId) > 0 {
			err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
			if err != nil {
				e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service RemoveLive error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	cortexOutputs := make([]live_schedule.CortexOutput, 0, 5)
	err = tx.Model(live_schedule.CortexOutput{}).Where("channel_id in ?", d.Ids).Find(&cortexOutputs).Error
	if err != nil {
		e.Log.Errorf("get CortexOutput error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	for _, v := range cortexOutputs {
		v := v
		if len(v.SwitchTaskId) > 0 {
			streamHubService.DeleteSwitchSourceTask(&StreamHubDto.SwitchSourceReq{TenantId: v.TenantId, Id: v.SwitchTaskId})
			if err != nil {
				e.Log.Errorf("DeleteSwitchSourceTask error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	//删除审核任务任务
	auditTasks := make([]live_schedule.AuditTask, 0, 5)
	err = tx.Model(&live_schedule.AuditTask{}).Where("channel_id in ?", d.Ids).Find(&auditTasks).Error
	if err != nil {
		e.Log.Errorf("get AuditTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	auditIds := make([]int, 0, 5)
	for _, v := range auditTasks {
		v := v
		auditIds = append(auditIds, v.Id)
		if len(v.TaskId) > 0 {
			err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
			if err != nil {
				e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service RemoveLive error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

		if len(v.PullTaskId) > 0 {
			err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
			if err != nil {
				e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

		if len(v.AuditTaskId) > 0 {
			err = baiduService.StopAudit(&baiduDto.StopAuditReq{TaskId: v.AuditTaskId, TenantId: v.TenantId})
			if err != nil {
				e.Log.Errorf("Service StopAudit error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	err = tx.Model(&live_schedule.AuditTask{}).Where("id in ?", auditIds).Delete(&auditTasks).Error
	if err != nil {
		e.Log.Errorf("delete AuditTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//获取录制任务
	recordTasks := make([]live_schedule.SourceRecordTask, 0, 5)
	err = tx.Model(live_schedule.SourceRecordTask{}).Where("channel_id in ?", d.Ids).Find(&recordTasks).Error
	if err != nil {
		e.Log.Errorf("get SourceRecordTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	//删除录制阵任务
	for _, v := range recordTasks {
		if len(v.RecordTaskId) > 0 {
			//先停用
			err = streamHubService.StopStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.RecordTaskId})
			if err != nil {
				e.Log.Errorf("Service StopStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}

			//在删除
			err = streamHubService.DeleteStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.RecordTaskId})
			if err != nil {
				e.Log.Errorf("Service DeleteStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service StopLiveReq error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	transCodeTasks := make([]live_schedule.ChannelTransCodeTask, 0, 5)
	err = tx.Model(live_schedule.ChannelTransCodeTask{}).Where("channel_id in ?", d.Ids).Find(&transCodeTasks).Error
	if err != nil {
		e.Log.Errorf("Service getChannelTransCodeTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	for _, v := range transCodeTasks {
		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service StopLiveReq error:%s \r\n", err)
				tx.Rollback()
				return err
			}
			if len(v.TaskId) > 0 {
				err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
				if err != nil {
					e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
					tx.Rollback()
					return err
				}
			}
			if len(v.TransTaskId) > 0 {
				err = streamHubService.RemoveTransCodeTask(&StreamHubDto.TransCodeReq{TenantId: v.TenantId, Id: v.TransTaskId})
				if err != nil {
					e.Log.Errorf("Service RemoveTransCodeTask error:%s \r\n", err)
					tx.Rollback()
					return err
				}
			}
		}
	}

	//水印任务
	waterMarkTransTasks := make([]live_schedule.WaterMarkTransTask, 0, 5)
	err = tx.Model(live_schedule.WaterMarkTransTask{}).Where("channel_id in ?", d.Ids).Find(&waterMarkTransTasks).Error
	if err != nil {
		e.Log.Errorf("Service waterMarkTransTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	for _, v := range waterMarkTransTasks {
		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service StopLiveReq error:%s \r\n", err)
				tx.Rollback()
				return err
			}
			if len(v.TaskId) > 0 {
				err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
				if err != nil {
					e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
					tx.Rollback()
					return err
				}
			}
			if len(v.WatermarkTaskId) > 0 {
				err = streamHubService.RemoveWatermarkTask(&StreamHubDto.RemoveWatermarkTaskReq{TenantId: v.TenantId, TaskId: v.WatermarkTaskId})
				if err != nil {
					e.Log.Errorf("Service RemoveWatermarkTask error:%s \r\n", err)
					tx.Rollback()
					return err
				}
			}
		}
	}

	//转码任务
	channelTransCodeTasks := make([]live_schedule.ChannelTransCodeTask, 0, 5)
	err = tx.Model(live_schedule.ChannelTransCodeTask{}).Where("channel_id in ?", d.Ids).Find(&channelTransCodeTasks).Error
	if err != nil {
		e.Log.Errorf("get channelTransCodeTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	for _, v := range channelTransCodeTasks {
		if len(v.LiveId) > 0 {
			err = liveService.RemoveLive(&liveDto.StopLiveReq{TenantId: v.TenantId, LiveId: v.LiveId})
			if err != nil {
				e.Log.Errorf("Service StopLiveReq error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
		if len(v.TaskId) > 0 {
			err = streamHubService.RemoveStreamHub(&StreamHubDto.StreamHubReq{TenantId: v.TenantId, Id: v.TaskId})
			if err != nil {
				e.Log.Errorf("Service RemoveStreamHub error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
		if len(v.TransTaskId) > 0 {
			err = streamHubService.RemoveTransCodeTask(&StreamHubDto.TransCodeReq{TenantId: v.TenantId, Id: v.TransTaskId})
			if err != nil {
				e.Log.Errorf("Service RemoveTransCodeTask error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}

	}

	//删除上车点和媒体处理关系
	err = tx.Model(live_schedule.UpMedia{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.UpMedia{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveUpMedia error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	//删除下车点和媒体处理关系
	err = tx.Model(live_schedule.MediaOff{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.MediaOff{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveMediaOff error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//删除上车点
	err = tx.Model(live_schedule.TrafficOn{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.TrafficOn{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveTrafficOn error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//删除下车点
	err = tx.Model(live_schedule.TrafficOff{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.TrafficOff{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveTrafficOn error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//删除媒体处理
	err = tx.Model(live_schedule.MediaProcess{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.MediaProcess{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveTrafficOn error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err = tx.Model(live_schedule.ChannelTask{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.ChannelTask{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveChannelTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	err = tx.Model(live_schedule.CortexTask{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.CortexTask{}).Error
	if err != nil {
		e.Log.Errorf("Service RemoveChannelTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	err = tx.Model(live_schedule.SourceRecordTask{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.SourceRecordTask{}).Error
	if err != nil {
		e.Log.Errorf("Remove SourceRecordTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	err = tx.Model(live_schedule.ChannelTransCodeTask{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.ChannelTransCodeTask{}).Error
	if err != nil {
		e.Log.Errorf("Remove ChannelTransCodeTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	err = tx.Model(live_schedule.WaterMarkTransTask{}).Where("channel_id in ?", d.Ids).Delete(&live_schedule.WaterMarkTransTask{}).Error
	if err != nil {
		e.Log.Errorf("Remove WaterMarkTransTask error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	for _, v := range sources {
		v := v
		if v.Kind == 2 {
			err = sourceBasicService.DeleteCustomSource(v)
			if err != nil {
				e.Log.Errorf("DeleteCustomSource error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	err = tx.Model(live_schedule.ChannelBasic{}).Where("id in ?", d.Ids).Delete(&live_schedule.ChannelBasic{}).Error
	if err != nil {
		e.Log.Errorf("Remove ChannelBasic error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (e *ChannelBasicService) GetChannelsBySource(d *dto.GetChannelsBySourceReq) (*[]live_schedule.ChannelBasic, error) {
	e.Log.Trace("通过信源获取调度任务")
	channels := make([]live_schedule.ChannelBasic, 0, 5)

	err := e.Orm.Model(&live_schedule.ChannelBasic{}).Where("tenant_id = ?", d.TenantId).Find(&channels).Error
	if err != nil {
		e.Log.Errorf("get ChannelBasic error:%s \r\n", err)
		return nil, err
	}

	channels2 := make([]live_schedule.ChannelBasic, 0, 5)
	for _, channelBasic := range channels {
		channelBasic := channelBasic
		if len(channelBasic.NewChartData) <= 0 {
			continue
		}
		chartData := live_schedule.ChartData{}
		err = json.Unmarshal([]byte(channelBasic.NewChartData), &chartData)
		if err != nil {
			e.Log.Errorf("Unmarshal chartData error:%s \r\n", err)
			return nil, err
		}
		for _, datum := range chartData.NodeData {
			if datum.Node.Data.Type == "input" {
				if datum.Node.Data.FormData.SourceId == d.SourceId {
					channels2 = append(channels2, channelBasic)
					break
				}
			}
		}

	}

	//err := e.Orm.Model(live_schedule.UpMedia{}).
	//	Distinct("channel_basic.channel_name").
	//	Select("channel_basic.id,channel_basic.channel_name,channel_basic.channel_state,channel_basic.id,channel_basic.is_time").
	//	Joins("left join channel_basic on channel_basic.id = up_media.channel_id").
	//	Joins("left join traffic_on on traffic_on.id = up_media.up_id").
	//	Where("traffic_on.source_id = ? and traffic_on.tenant_id=? and channel_basic.is_delete=2", d.SourceId, d.TenantId).
	//	Find(&channels2).
	//	Error
	//if err != nil {
	//	e.Log.Errorf("Service GetChannelsBySource error:%s \r\n", err)
	//	return nil, err
	//}
	//channels = append(channels, channels2...)
	return &channels2, nil
}

func (e *ChannelBasicService) GetChannelTaskStatistics(c *dto.GetChannelTaskStatisticsReq) (dto.ChannelTaskStatistics, error) {

	basics := make([]live_schedule.ChannelBasic, 0, 5)
	tasks := make([]live_schedule.ChannelTask, 0, 5)
	data := dto.ChannelTaskStatistics{}

	////获取信源基本任务
	//db := e.Orm.Model(live_schedule.ChannelBasic{})
	//if len(c.TenantId) > 0 {
	//	db.Where("tenant_id=?", c.TenantId)
	//}
	//err := db.Find(&basics).Error
	var count int64
	err := e.GetPage(&dto.ChannelBasicGetPageReq{Pagination: commonDto.Pagination{PageIndex: 1, PageSize: 10000}, TenantId: c.TenantId, IsDelete: 2}, &basics, &count)
	if err != nil {
		e.Log.Errorf("GetChannelTaskStatistics error:%s \r\n", err)
		return data, err
	}

	ids := make([]int, 0, 5)
	for _, v := range basics {
		ids = append(ids, v.Id)
	}

	//获取信源任务详情
	err = e.Orm.Model(live_schedule.ChannelTask{}).Where("channel_id in ?", ids).Find(&tasks).Error
	if err != nil {
		e.Log.Errorf("GetChannelTask error:%s \r\n", err)
		return data, err
	}

	taskMap := make(map[int][]live_schedule.ChannelTask)
	for _, task := range tasks {
		task := task
		v, ok := taskMap[task.ChannelId]
		if !ok {
			v = make([]live_schedule.ChannelTask, 0, 5)
		}
		v = append(v, task)
		taskMap[task.ChannelId] = v
	}

	//统计数据
	data.TotalCount = len(basics)
	fail := 0
	suc := 0
	off := 0
	for _, b := range basics {
		if b.ChannelState == 3 {
			fail++
			continue
		}
		if b.ChannelState == 2 {
			off++
			continue
		}
		suc++

	}
	data.FailCount = fail
	data.NormalCount = suc
	data.OffCount = off

	return data, nil
}

func (e *ChannelBasicService) EnableOrCancelTimeTask(c *dto.EnableOrCancelTimeTaskReq) error {

	err := e.Orm.Model(&live_schedule.CycleTime{}).Where("channel_id=?", c.ChannelId).Delete(&live_schedule.CycleTime{}).Error
	if err != nil {
		e.Log.Errorf("delete CycleTime error:%s \r\n", err)
		return err
	}
	var basic live_schedule.ChannelBasic
	err = e.Orm.Model(live_schedule.ChannelBasic{}).Where("tenant_id=? and id=?", c.TenantId, c.ChannelId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("GetChannelBasic error:%s \r\n", err)
		return err
	}
	if basic.ChannelState != 2 {
		return errors.New(string(apis.CreateTimeTaskError.Code))
	}

	now := time.Now().Unix()

	if int64(c.EndTime) <= now {
		return errors.New("结束时间不能小于当前时间")
	}

	param := make(map[string]interface{})
	param["start_time"] = c.StartTime
	param["end_time"] = c.EndTime
	param["time_type"] = c.TimeType
	param["cycle_end_time"] = c.CycleEndTime
	param["weekly"] = c.Weekly
	param["update_time"] = now
	param["is_time"] = basic.IsTime

	err = e.Orm.Model(live_schedule.ChannelBasic{}).Where("tenant_id=? and id=?", c.TenantId, c.ChannelId).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("EnableOrCancelTimeTask error:%s \r\n", err)
		return err
	}

	err = e.GenerateCycleTime(&dto.GenerateCycleTimeReq{ChannelId: c.ChannelId})
	if err != nil {
		e.Log.Errorf("GenerateCycleTime error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *ChannelBasicService) StartOrStopTimeTask(c *dto.StartOrStopTimeTaskReq) error {

	var basic live_schedule.ChannelBasic
	err := e.Orm.Model(live_schedule.ChannelBasic{}).Where("id=?", c.ChannelId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("GetChannelBasic error:%s \r\n", err)
		return err
	}
	param := make(map[string]interface{})
	param["is_time"] = c.IsTime
	if c.IsTime == 2 {
		param["start_time"] = 0
		param["end_time"] = 0
		param["time_type"] = 1
		param["cycle_end_time"] = 0
		param["weekly"] = ""
	}

	err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("id=?", c.ChannelId).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("StartTimeTask error:%s \r\n", err)
		return err
	}

	if c.IsTime == 2 {
		err = e.Orm.Model(&live_schedule.CycleTime{}).Where("channel_id =?", c.ChannelId).Delete(&live_schedule.CycleTime{}).Error
		if err != nil {
			e.Log.Errorf("delete CycleTime error:%s \r\n", err)
			return err
		}
	} else {
		err = e.GenerateCycleTime(&dto.GenerateCycleTimeReq{ChannelId: c.ChannelId})
		if err != nil {
			e.Log.Errorf("GenerateCycleTime error:%s \r\n", err)
			return err
		}
	}
	return nil
}

func (e *ChannelBasicService) SaveCycleTime(c *dto.SaveCycleTimeReq) error {

	channelId := 0
	if len(c.CycleTimes) > 0 {
		channelId = c.CycleTimes[0].ChannelId
	}
	//else {
	//	err := e.GenerateCycleTime(&dto.GenerateCycleTimeReq{ChannelId: c.ChannelId})
	//	if err != nil {
	//		e.Log.Errorf("GenerateCycleTime error:%s \r\n", err)
	//		return err
	//	}
	//}
	var basic live_schedule.ChannelBasic
	err := e.Orm.Model(live_schedule.ChannelBasic{}).Where("id=?", channelId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("GetChannelBasic error:%s \r\n", err)
		return err
	}

	for _, cycleTime := range c.CycleTimes {
		if cycleTime.StartTime > cycleTime.EndTime {
			return errors.New(string(apis.TimeError.Code))
		}
		if basic.TimeType == 3 || basic.TimeType == 4 {
			start := time.Unix(cycleTime.StartTime, 0)
			weekDay := int(start.Weekday())
			if !strings.Contains(basic.Weekly, strconv.Itoa(weekDay)) {
				return errors.New(string(apis.WeekTimeError.Code))
			}
		}
	}

	if basic.IsTime == 2 || basic.TimeType == 1 || basic.ChannelState != 2 {
		return err
	}
	err = e.Orm.Save(&c.CycleTimes).Error
	if err != nil {
		e.Log.Errorf("save CycleTime error:%s \r\n", err)
		return err
	}

	return nil
}

func (e *ChannelBasicService) GetCycleTime(c *dto.GetCycleTimeReq, cycleTimes *[]live_schedule.CycleTime, count *int64) error {

	var basic live_schedule.ChannelBasic
	err := e.Orm.Model(live_schedule.ChannelBasic{}).Where("id=?", c.ChannelId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("GetChannelBasic error:%s \r\n", err)
		return err
	}
	if basic.IsTime == 2 || basic.TimeType == 1 {
		return err
	}

	now := time.Now().Unix()
	data := live_schedule.CycleTime{}
	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Where("channel_id =? and time_type=? and end_time>?", c.ChannelId, basic.TimeType, now).
		Find(cycleTimes).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("GetCycleTime GetPage error:%s \r\n", err)
		return err
	}
	if len(*cycleTimes) > 0 {
		if (*cycleTimes)[0].StartTime < now && (*cycleTimes)[0].EndTime > now {
			(*cycleTimes)[0].IsRunning = 1
		}
	}

	return nil
}

func (e *ChannelBasicService) DeleteCycleTime(c *dto.DeleteCycleTimeReq) error {

	err := e.Orm.Model(&live_schedule.CycleTime{}).Where("channel_id =?", c.ChannelId).Delete(&live_schedule.CycleTime{}).Error
	if err != nil {
		e.Log.Errorf("delete CycleTime error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *ChannelBasicService) GenerateCycleTime(c *dto.GenerateCycleTimeReq) error {

	res := make([]live_schedule.CycleTime, 0, 5)
	var basic live_schedule.ChannelBasic
	err := e.Orm.Model(live_schedule.ChannelBasic{}).Where("id=?", c.ChannelId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("GetChannelBasic error:%s \r\n", err)
		return err
	}

	cycleTimes := make([]live_schedule.CycleTime, 0, 5)
	err = e.Orm.Model(&live_schedule.CycleTime{}).Where("channel_id =? and time_type=?", c.ChannelId, basic.TimeType).Order("start_time desc").Find(&cycleTimes).Error
	if err != nil {
		e.Log.Errorf("get CycleTime error:%s \r\n", err)
		return err
	}
	var startTime int64
	var endTime int64
	if len(cycleTimes) > 0 {
		if basic.TimeType != 3 {
			startTime = cycleTimes[0].StartTime + 60*60*24
			endTime = cycleTimes[0].EndTime + 60*60*24
		} else {
			startTime = cycleTimes[0].StartTime + 60*60*24*7
			endTime = cycleTimes[0].EndTime + 60*60*24*7
		}
	} else {
		startTime = basic.StartTime
		endTime = basic.EndTime
	}

	switch basic.TimeType {
	case 2:
		for i := 0; i < 10; i++ {
			cycleTime := live_schedule.CycleTime{}
			cycleTime.TenantId = basic.TenantId
			cycleTime.ChannelId = basic.Id
			cycleTime.TimeType = basic.TimeType
			st := time.Unix(startTime, 0)
			et := time.Unix(endTime, 0)
			cycleTime.IsCancel = 2
			cycleTime.StartTime = st.AddDate(0, 0, i).Unix()
			cycleTime.EndTime = et.AddDate(0, 0, i).Unix()
			if basic.CycleEndTime < cycleTime.StartTime && basic.CycleEndTime > 0 {
				continue
			}
			res = append(res, cycleTime)
		}
	case 3:
		for i := 0; i < 10; i++ {
			cycleTime := live_schedule.CycleTime{}
			cycleTime.TenantId = basic.TenantId
			cycleTime.ChannelId = basic.Id
			cycleTime.TimeType = basic.TimeType
			st := time.Unix(startTime, 0)
			et := time.Unix(endTime, 0)
			cycleTime.IsCancel = 2
			cycleTime.StartTime = st.AddDate(0, 0, i*7).Unix()
			cycleTime.EndTime = et.AddDate(0, 0, i*7).Unix()
			if basic.CycleEndTime < cycleTime.StartTime && basic.CycleEndTime > 0 {
				continue
			}
			res = append(res, cycleTime)
		}
	case 4:
		lastStartTime := time.Unix(startTime, 0)
		lastEndTime := time.Unix(endTime, 0)
		for i := 0; i < 10; i++ {
			cycleTime := live_schedule.CycleTime{}
			cycleTime.TenantId = basic.TenantId
			cycleTime.ChannelId = basic.Id
			cycleTime.TimeType = basic.TimeType
			cycleTime.IsCancel = 2
			e.Log.Trace(lastStartTime, lastStartTime.Weekday())
			if lastStartTime.Weekday() == time.Friday && i != 0 {
				lastStartTime = lastStartTime.AddDate(0, 0, 3)
				lastEndTime = lastEndTime.AddDate(0, 0, 3)
			} else if lastStartTime.Weekday() == time.Saturday {
				lastStartTime = lastStartTime.AddDate(0, 0, 2)
				lastEndTime = lastEndTime.AddDate(0, 0, 2)
			} else {
				if i != 0 {
					lastStartTime = lastStartTime.AddDate(0, 0, 1)
					lastEndTime = lastEndTime.AddDate(0, 0, 1)
				}
			}

			fmt.Println("MMMMMMMM:", lastStartTime)
			cycleTime.StartTime = lastStartTime.Unix()
			cycleTime.EndTime = lastEndTime.Unix()
			if basic.CycleEndTime < cycleTime.StartTime && basic.CycleEndTime > 0 {
				continue
			}

			res = append(res, cycleTime)
		}
	}

	if len(res) > 0 {
		err = e.Orm.Save(&res).Error
		if err != nil {
			e.Log.Errorf("save CycleTime error:%s \r\n", err)
			return err
		}
	}

	return nil
}

func (e *ChannelBasicService) CancelCycleTime(c *dto.CancelCycleTimeReq) error {

	err := e.Orm.Model(&live_schedule.CycleTime{}).Where("id =?", c.Id).Update("is_cancel", 1).Error
	if err != nil {
		e.Log.Errorf("update CycleTime error:%s \r\n", err)
		return err
	}
	return nil
}
